package demo.service.impl;

import demo.model.User;
import demo.service.UserService;
import demo.service.base.BaseServiceImpl;
import demo.utils.ServerResponse;
import jdk.nashorn.internal.runtime.ECMAException;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.concurrent.TimeUnit;

@Service("userService")
@Transactional  // 回滚(事务)
public class UserServiceImpl extends BaseServiceImpl<User> implements UserService {

    @Override
    public ServerResponse delete(int id) {
        int sum = getCountById(id);
        if(sum==0)
        {
            return ServerResponse.createByError("该编号不存在");
        }
        try
        {
            userMapper.delete(id);
            return ServerResponse.createBySuccessMsg("删除成功");
        }catch (Exception e)
        {
            return ServerResponse.createByError("删除失败");
        }
    }

    @Override
    public ServerResponse update(User user) {

        try
        {
            System.out.println("user : "+user);
            int sum = getCountById(user.getId());
            if(sum==0)
            {
                return ServerResponse.createByError("更新失败，该数据不存在");
            }
            User u = select(user.getId());
            if(u.equals(user))
            {
                return ServerResponse.createBySuccessMsg("用户数据未作修改");
            }
            if(user.getAge()!=0)
            {
                u.setAge(user.getAge());
            }
            if(user.getName()!=null)
            {
                u.setName(user.getName());
            }
            if(user.getDate()!=null)
            {
                u.setDate(user.getDate());
            }
            userMapper.update(u);
            return ServerResponse.createBySuccessMsg("更新成功");
        }catch (Exception e)
        {
            e.printStackTrace();
            return ServerResponse.createByError("更新失败");
        }

    }

    public User select(int id)
    {
        return (User)userMapper.get(id);
    }

    @Override
    public ServerResponse get(int id) {
        int sum = getCountById(id);
        if(sum==0)
        {
            return ServerResponse.createByError("该用户的编号不存在");
        }
        User user =(User) userMapper.get(id);
        return ServerResponse.createBySuccess("用户数据",user);
    }

    public List<User> findAll2()
    {
        List<User> list = userMapper.findAll();
        return list;
    }

    @Override
    public ServerResponse findAll() {
        List<User> list = userMapper.findAll();
        if(list.isEmpty())
        {
            return ServerResponse.createBySuccessMsg("暂无数据");
        }
        return ServerResponse.createBySuccess("查询成功，数据如下",list);
    }

    @Override
    public int getCountById(int id) {
        return userMapper.getCountById(id);
    }

    @Override
    public ServerResponse getyName(String name) {

//        System.out.println(name);
        List<User> user = null;
        try
        {
            user = userMapper.getyName(name);
        }catch (Exception e)
        {
            System.out.println("出错了");
//            e.printStackTrace();
        }

        if(user.isEmpty())
        {
            return ServerResponse.createByError("用户名不存在");
        }
        return ServerResponse.createBySuccess("用户数据",user);
    }


    //    redis   查询
    public ServerResponse findUerById(int id)
    {
        String key = "user_"+id;   //redis
        ValueOperations<String,User> operations = redisTemplate.opsForValue();   //redis
        boolean hasKey = redisTemplate.hasKey(key);   //redis
        long start = System.currentTimeMillis();  //计算耗时
        if(hasKey)   //redis   该id在缓存中
        {
            User user = operations.get(key);   //从缓存中获取
            System.out.println("redis : user : find : "+user);
            long end = System.currentTimeMillis();
            System.out.println("总共耗时："+(end-start )+"ms  (缓存)");
            return ServerResponse.createBySuccess("用户数据",user);
        }   //redis
        else    //该id不在缓存中
        {
            User user = (User) userMapper.get(id);
            int count = getCountById(user.getId());
            if (count==0)
            {
                return ServerResponse.createByError("该用户的编号不存在");
            }
            operations.set(key,user,5, TimeUnit.HOURS);   //既然该id的数据不存在就把该数据放到缓存中
            long end = System.currentTimeMillis();
            System.out.println("总共耗时："+(end-start )+"ms");
            return ServerResponse.createBySuccess("用户数据",user);

        }
    }
    //    redis   查询

    //    redis   更新
    @Override
    public ServerResponse updateRedis(User user) {
        ValueOperations<String,User> operations = redisTemplate.opsForValue();  //先获取缓存
        try
        {
            System.out.println("redis : user : update : "+user);
            int sum = getCountById(user.getId());
            if(sum==0)
            {
                return ServerResponse.createByError("更新失败，该数据不存在");
            }
            User u = select(user.getId());
            if(u.equals(user))
            {
                return ServerResponse.createBySuccessMsg("用户数据未作修改");
            }
            if(user.getAge()!=0)
            {
                u.setAge(user.getAge());
            }
            if(user.getName()!=null)
            {
                u.setName(user.getName());
            }
            if(user.getDate()!=null)
            {
                u.setDate(user.getDate());
            }
            userMapper.update(u);
            String key = "user_"+user.getId();   //看看该id在不在缓存中
            boolean hasKey = redisTemplate.hasKey(key);//看看该id在不在缓存中
            if (hasKey) //如果在缓存中将其删除
            {
                redisTemplate.delete(key);
                System.out.println("删除缓存中的key=========>" + key);
            }
            User userNew = (User) findUerById(user.getId()).getData();  // 查询一下
            if(userNew!=null)  // 如果数据不为空则重新放到缓存中
            {
                operations.set(key,userNew,3,TimeUnit.HOURS);
                System.out.println("成功刷新缓存");
            }
            return ServerResponse.createBySuccessMsg("更新成功");
        }catch (Exception e)
        {
            e.printStackTrace();
            return ServerResponse.createByError("更新失败");
        }
    }

    //    redis   更新

    //    redis   删除
    @Override
    public ServerResponse deleteRedis(int id) {
        ValueOperations<String,User> operations = redisTemplate.opsForValue();  //先获取缓存
        int count = getCountById(id);
        if(count==0)
        {
            return ServerResponse.createByError("该数据不存在");
        }
        try
        {
            userMapper.delete(id);
            String key = "user_"+id;
            boolean hasKey = redisTemplate.hasKey(key);
            if (hasKey)
            {
                redisTemplate.delete(key);
                System.out.println("该数据缓存删除成功");
            }
            return ServerResponse.createBySuccessMsg("删除成功");
        }catch (Exception e)
        {
            e.printStackTrace();
            return ServerResponse.createByError("删除失败");
        }

    }
    //    redis   删除

    //    redis   添加
    @Override
    public ServerResponse insert(User user) {
        ValueOperations<String,User> operations = redisTemplate.opsForValue();  //先获取缓存
        try
        {
            int sum = getCountById(user.getId());
            if(sum!=0)
            {
                return ServerResponse.createByErrorMsg2("该编号的数据已存在");
            }
            List<User> list = findAll2();
            if(list!=null)
            {
                for(User u : list)
                {
                    if(u.equals(user))
                    {
                        return ServerResponse.createByErrorMsg2("该数据已存在");
                    }
                }
            }

            userMapper.insert(user);
            String key = "user_"+user.getId();
            boolean hasKey = redisTemplate.hasKey(key);
            if(!hasKey)
            {
                operations.set(key,user,5, TimeUnit.HOURS);   //既然该id的数据不存在就把该数据放到缓存中
                System.out.println("已将新添加的数据放入了缓存");
            }
            return ServerResponse.createBySuccessMsg("添加成功");
        }
        catch (Exception e)
        {
            return ServerResponse.createByError("添加失败");
        }
    }
    //    redis   添加


}
